package ms.jasim.model.editor.views;

import java.util.HashMap;

import org.eclipse.jface.text.Document;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.TextViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CCombo;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Composite;

import swing2swt.layout.BorderLayout;

import com.swtdesigner.SWTResourceManager;

public class ConsoleViewComposite extends Composite {

	private StyledText widget;
	private CCombo combo;
	private StackLayout stackLayout;
	private HashMap<String, TextViewer> sessions;
	private Composite composite;
	/**
	 * Create the composite
	 * @param parent
	 * @param style
	 */
	public ConsoleViewComposite(Composite parent, int style) {
		super(parent, style);
		this.setLayout(new BorderLayout(0, 0));

		combo = new CCombo(this, SWT.BORDER);
		combo.setEditable(false);
		combo.setLayoutData(BorderLayout.NORTH);
		combo.addSelectionListener(new SelectionAdapter() {
			
			@Override
			public void widgetSelected(SelectionEvent e) {
				activateSession(combo.getText(), true);
			}
		});
		
		composite = new Composite(this, SWT.NONE);
		stackLayout = new StackLayout();
		composite.setLayout(stackLayout);
		composite.setLayoutData(BorderLayout.CENTER);
		//
	}

	IDocument getDocument(String session) {
		if (this.sessions == null)
			this.sessions = new HashMap<String, TextViewer>();
		IDocument result = null;
		if (!sessions.containsKey(session)) {
			TextViewer viewer = new TextViewer(composite, SWT.V_SCROLL | SWT.H_SCROLL);
			viewer.setDocument(new Document());
			widget = viewer.getTextWidget();
			widget.setFont(SWTResourceManager.getFont("Courier New", 9, SWT.NONE));
			sessions.put(session, viewer);
			result = viewer.getDocument();
			combo.add(session);
		}
		else result = sessions.get(session).getDocument();
		return result;
	}
	
	public void activateSession(String session, boolean force) {
		int selIdx = combo.getSelectionIndex();
		int newIdx = combo.indexOf(session);
		if (force || selIdx != newIdx) {
			combo.setText(session);
			TextViewer viewer = sessions.get(session);
			if (viewer != null) {
				stackLayout.topControl = viewer.getControl();
				composite.layout();
			}
		}
	}
	
	@Override
	protected void checkSubclass() {
		// Disable the check that prevents subclassing of SWT components
	}

	public void clearAll() {
		if (sessions != null)
			for (TextViewer viewer: sessions.values())
				viewer.getDocument().set("");
	}

}
